<template>
  <div class="role">
    <page-search
      :search-config="searchConfig"
      @query-click="handleQueryClick"
      @reset-click="handleResetClick"
    ></page-search>
    <page-content
      :content-config="contentConfig"
      ref="contentRef"
      @new-click="handleNewBtnClick"
      @edit-click="handleEditBtnClick"
    ></page-content>
    <page-modal ref="modalRef" :modal-config="modalConfig" :other-info="otherInfo">
      <template #menuList>
        <el-tree
          ref="treeRef"
          :data="entireMenus"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleElTreeCheck"
        >
        </el-tree>
      </template>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { nextTick, ref } from 'vue'
import { mapMenuListToIds } from '@/utils/map-menus'
import type { ElTree } from 'element-plus'
import PageSearch from '@/components/page-search/PageSearch.vue'
import searchConfig from './config/search.config'
import PageContent from '@/components/page-content/PageContent.vue'
import PageModal from '@/components/page-modal/PageModal.vue'
import contentConfig from './config/content.config'
import usePageContent from '@/hooks/usePageContent'
import usePageModal from '@/hooks/usePageModal'
import modalConfig from './config/modal.config'
import useMainStore from '@/store/main/main'

const { contentRef, handleQueryClick, handleResetClick } = usePageContent()
const { modalRef, handleNewBtnClick, handleEditBtnClick } = usePageModal(newCallback, editCallback)

const mainStore = useMainStore()
const { entireMenus } = storeToRefs(mainStore)

const otherInfo = ref({})

function handleElTreeCheck(data1: any, data2: any) {
  // console.log(data2)
  const menuList = [...data2.checkedKeys, ...data2.halfCheckedKeys]
  // console.log(menuList)
  otherInfo.value = { menuList }
}

const treeRef = ref<InstanceType<typeof ElTree>>()
function newCallback() {
  nextTick(() => {
    treeRef.value?.setCheckedKeys([])
  })
}
function editCallback(itemData: any) {
  // 这里为什么要使用nextTick
  // nextTick:当DOM操作完成后，DOM树更新完成，再执行里面的操作
  // 这里是我首先执行mapMenuListToIds函数后执行里面第一个内容modalRef.value!.setModalVisible(false, itemData)
  // 然后执行setModalVisible函数的内容centerDialogVisible.value = true
  // 由于更改响应式数据的时候，DOM更新不是立马就更新的，而是有时间间隔等多个数据一起统一更新
  // 当在Vue中更改响应式状态时，最终的DOM更新并不是同步生效的，而是由Vue将它们缓存在一个队列中，直到下一个“tick”才一起执行。这样是为了确保每个组件无论发生多少状态改变,都仅执行—次更新。
  // 但是执行完centerDialogVisible.value = true，数据虽然改变了但是DOM没更新，所以新建编辑modal窗口并未创建展示，
  // 执行treeRef.value?.setCheckedKeys(menuIds)，由于el-tree是在modal里面的，modal都没创建，所以这条语句没效果，要放在DOM更新完后执行才有效果

  nextTick(() => {
    const menuIds = mapMenuListToIds(itemData.menuList)
    // console.log(menuIds)
    treeRef.value?.setCheckedKeys(menuIds)
  })
}
</script>

<style lang="less" scoped></style>
